<?php

namespace Frieza\Modules\Photo\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Circle\CircleBaseInfo;
use Doraemon\model\Member;
use Doraemon\model\TopicActivity;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\service\Photo\answerListSearch;
use Doraemon\service\Photo\ListSearch;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Frieza\Modules\Photo\Extensions\BottomRow;
use Frieza\Modules\Photo\Extensions\FoldRow;
use Frieza\Modules\Photo\Extensions\RemoveRow;
use Frieza\Modules\Photo\Extensions\UnBottomRow;
use Frieza\Modules\Photo\Extensions\UnFoldRow;
use Frieza\Modules\Photo\Extensions\SetHot;
use Frieza\Modules\Photo\Extensions\CancelHot;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AnswerController extends Controller
{
    public function index(Content $content, Request $request)
    {
        //圈子信息
        $circleList = CircleBaseInfo::getNameId();
        $params = $request->all();
        if (!isset($params['release_time'])) {
            $params['release_time'] = [
                'start' => '2016-01-01 00:00:00',
                'end' => date('Y-m-d H:i:s'),
            ];
            $request->merge([
                'release_time' => $params['release_time'],
            ]);
        }

        if (!isset($params['per_page'])) {
            $params['per_page'] = 20;
        }

        //查出话题标题
        $exportParams = [];
        try {
            if ($params['topic_activity_title']) {
                // 在话题名称前面拼接上#号，方便从内容中匹配话题
                $params['topic_activity_title'] = '#'.$params['topic_activity_title'];
            } else {
                $params['topic_activity_title'] = '#';
            }
            $exportParams = http_build_query($params);
            $res = answerListSearch::getList(new ListSearch($params));
//            $res['rows'] = ['000d9tp00005c7mb','000d9tq00000098d','000d9tr00000098d'];
            $photos = \Doraemon\service\Photos::getMultiPhotoInfos($res['rows'], null);// 通过id获取图片信息
        } catch (\Exception $e) {
            $res = ['total' => 0];
            $photos = [];
        }

        $options = [
            'perPage' => $params['per_page'],
        ];

        $gridModel = new pGridDataModel($this->formatPhoto($photos), $res['total'], $options);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($exportParams, $circleList) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            //$grid->disableActions();

            $grid->tools(function ($tools) use($exportParams) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
                $exportUrl = "/admin/photo/answer/export?{$exportParams}";
                $tools->append("<a href='$exportUrl' class='btn button-success'><i class='fa fa-file-excel-o'></i>>批量导出</a>");
            });

            $grid->filter(function (Grid\Filter $filter) use ($circleList) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->dropDown('time', [
                        'release_time' => '发布时间',
                    ])->betweenDatetime();

                    $filter->equal('high_check', '高级筛选')->checkbox([
                        'is_algorithm' => '算法打分',
                        'exclude_b2_and_b3' => '排除B2、B3用户',
                        'is_fold' => '仅看折叠内容',
                    ]);

                    $filter->equal('score', '分数')->checkbox([
                        1 => '未打分',
                        2 => '普通',
                        3 => '优质',
                        4 => '精选',
                    ]);

                    $filter->equal('photo_type', '类型')->checkbox([
                        1 => '无图',
                        2 => '单图',
                        3 => '多图',
                        4 => '视频',
                    ]);

                    $filter->dropDown('search_id', [
                        'photo_id' => '内容id',
                        'uid' => '用户id',
                    ]);
                });
                $filter->column(1 / 2, function ($filter) use ($circleList) {
                    $filter->equal('user_type', '用户身份')->checkbox(Member::$typeDesc);

                    $filter->equal('is_best', '是否加精')->checkbox([
                        1 => '是',
                        0 => '否',
                    ]);

                    $filter->equal('remark', '内容正文');
                    $filter->equal('topic_activity_title', '话题标题');
                    $filter->equal('circle_id', '圈子名称:')->select($circleList);
                });
            });

            $grid->column('photo_id', '内容id')->expand(function () {
                return $this->expand;
            }, true)->width(100);
            $grid->column('remark', '内容信息')->width(550)->display(function () {
                return "<strong>[标题]:</strong>{$this->title}<br><strong>[正文]:</strong>{$this->remark}";
            });
            $grid->column('addtime', '发布时间')->width(150);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('counter', '交互情况')->width(100)->display(function () {
                return "赞：{$this->counter['like']} <br/> 评论：{$this->counter['comments']}  <br/> 收藏：{$this->counter['favorite']}  <br/> 分享：{$this->counter['share']} ";
            });
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                // 去掉编辑
                $actions->disableEdit();
                // 去掉查看
                $actions->disableView();
                $actions->append(new BottomRow($actions->row->photo_id, $actions->row->is_bottom == 1));
                $actions->append(new UnBottomRow($actions->row->photo_id, $actions->row->is_bottom != 1));
                $actions->append(new FoldRow($actions->row->photo_id, $actions->row->is_fold == 1));
                $actions->append(new UnFoldRow($actions->row->photo_id, $actions->row->is_fold == 0));
//                $actions->append(new RemoveRow($actions->row->photo_id));

                $actions->append(new SetHot($actions->row->photo_id, $actions->row->is_best == 1));
                $actions->append(new CancelHot($actions->row->photo_id, $actions->row->is_best == 0));
            });
        });


        Admin::script($this->imgScript());
        Admin::script($this->operateScript());

        return $content
            ->header('内容列表')
            ->breadcrumb(
                ['text' => '话题列表', 'url' => '/topic/index'],
                ['text' => '内容列表', 'url' => '/photo/answer/list']
            )
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>")
            ->body($listGrid);

    }

    private function imgScript()
    {
        $operateUrl = route('photo.operate');

        return <<<SCRIPT
            let url = '{$operateUrl}'
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });
SCRIPT;
    }

    private function operateScript()
    {
        $operateUrl = route('photo.operate');

        return <<<SCRIPT
            $('.operate').click(function() {
                var _this = $(this);
                let noteId = $(this).data('id');
                let type = $(this).data('type');
                let url = '{$operateUrl}'
                
                let params = {note_id:noteId, type:type}
                
                $.post(url, params , function (e) {
                    if(e.code == 1) {
                        if(type == 'bottom') {
                            _this.html("取消置底");
                            _this.data("type", "unbottom");
                        } else if(type == 'unbottom') {
                            _this.html("置底");
                            _this.data("type", "bottom");
                        } else if(type == 'fold') {
                            _this.html("取消折叠");
                            _this.data("type", "unfold");
                        } else if(type == 'unfold') {
                            _this.html("折叠");
                            _this.data("type", "fold");
                        }
                        
                        toastr.success(e.msg, null, {
                            timeOut : 1000
                        });  
                    } else {
                        toastr.error(e.msg, null, {
                            timeOut : 1000
                        });
                    }
                });
            });
SCRIPT;
    }

    private function getPicExpand($picArr)
    {
        $row = new Row();
        if ($picArr['pics']) {
            $GirdModel = new pGridDataModel($picArr, null, ['pageName' => '']);
            $grid = new Grid($GirdModel);
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disableTools();
            $grid->disableActions();
            $grid->disableExport();
            $grid->column('pic', 'pic信息')->display(function () {
                $infos = json_decode($this, true);
                if ($infos && is_array($infos)) {
                    $pic = '';
                    foreach ($infos as $picInfo) {
                        if ($picInfo['is_video']) {
                            $pic .= "<div style='display:inline-block;margin:10px;height:220px;'>" .
                                "<video src='" . $picInfo['pic_url'] . "' height='300px' controls /></video>" .
                                "<br>" . $picInfo['pic_id'] . "</div>";
                        } else {
                            $pic .= "<div style='display:inline-block;margin:10px;height:220px;'>" .
                                "<img src='" . $picInfo['pic_url'] . "' height='200px' class='img' />" .
                                "<br>" . $picInfo['pic_id'] . "</div>";
                        }
                    }
                    return $pic;
                }
            });

            $grid->disablePagination();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->disableView();
            });
            $row->column('12', $grid);
            return $row->render();
        }
        return '';
    }

    private function formatPhoto(array $photos)
    {
        $res = [];
        $i = 0;
        foreach ($photos as $photo) {
            $picTmp = [];
            if ($photo['photo']['photo_info']['image_list']) {
                foreach ($photo['photo']['photo_info']['image_list'] as $p) {
                    $picTmp[] = [
                        'pic_url' => $p['pic_url'],
                        'pic_id' => $p['pic_id'],
                        'photo_id' => $photo['photo']['photo_info']['id'],
                        'is_video' => 0,
                    ];
                }
            } else {
                if ($photo['photo']['photo_info']['pic_url']) {
                    $picTmp[] = [
                        'pic_url' => $photo['photo']['photo_info']['pic_url'],
                        'pic_id' => $photo['photo']['photo_info']['pin_pic_id'],
                        'photo_id' => $photo['photo']['photo_info']['id'],
                        'is_video' => 0,
                    ];
                }
            }

            if ($photo['photo']['photo_info']['video_info']) {
                $picTmp[] = [
                    'pic_url' => $photo['photo']['photo_info']['video_info']['play_url_for_frieza'],
                    'pic_id' => $photo['photo']['photo_info']['video_info']['video_id'],
                    'photo_id' => $photo['photo']['photo_info']['id'],
                    'is_video' => 1,
                ];
                $picTmp[] = [
                    'pic_url' => $photo['photo']['photo_info']['video_info']['pic_url'],
                    'pic_id' => $photo['photo']['photo_info']['video_info']['cover_pic_id'],
                    'photo_id' => $photo['photo']['photo_info']['id'],
                    'is_video' => 0,
                ];
            }

            $res[] = [
                'id' => ++$i,
                'photo_id' => $photo['photo']['photo_info']['id'],
                'remark' => $this->highLight($photo['photo']['photo_info']['remark']),
                'title' => $photo['photo']['photo_info']['title'],
                'addtime' => date('Y-m-d H:i:s', $photo['photo']['photo_info']['addtime']),
                'uid' => $photo['photo']['user_info']['uid'],
                'user' => [
                    'uid' => $photo['photo']['user_info']['uid'],
                    'nick' => $photo['photo']['user_info']['nick'],
                    'type' => $photo['photo']['user_info']['type'],
                ],
                'counter' => $photo['photo']['counter'],
                'images' => $picTmp,
                'status' => $photo['photo']['photo_info']['status'],
                'is_best' => $photo['photo']['photo_info']['is_best'],
                'is_bottom' => $photo['photo']['photo_info']['is_bottom'],
                'is_fold' => $photo['photo']['photo_info']['is_fold'],
                'expand' => $this->getPicExpand(['pics' => $picTmp]) . $this->_getDivLine(),
                'topic_title' => $photo['photo']['photo_info']['topic']['title'],
            ];
        }

        return $res;
    }

    /**
     * 分割线
     * @return string
     */
    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }

    public static function export(Request $request)
    {
        $params = $request->all();
        if (!isset($params['release_time'])) {
            $params['release_time'] = [
                'start' => '2016-01-01 00:00:00',
                'end' => date('Y-m-d H:i:s'),
            ];
            $request->merge([
                'release_time' => $params['release_time'],
            ]);
        }

        if (!isset($params['per_page'])) {
            $params['per_page'] = 20;
        }

        $res = answerListSearch::getList(new ListSearch($params));
        $photos = \Doraemon\service\Photos::getPhotoInfos($res['rows'], null);// 通过id获取图片信息

        if (empty($photos)) {
            $error = new MessageBag([
                'title' => '导出数据为空'
            ]);
            return back()->with(compact('error'));
        }

        // 内容ID、内容链接、内容标题、内容正文、发布时间、uid、昵称、点赞数、评论数、收藏数
        $downExcel = new DownExcel();
        $title = "内容数据";
        $downExcel->setFrontBold('1');
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);
        $widths = [
            'A' => 10,
            'B' => 15,
            'C' => 15,
            'D' => 100,
            'E' => 15,
            'F' => 30,
            'G' => 20,
            'H' => 15,
            'I' => 15,
            'J' => 15,
            'K' => 15,
        ];
        $downExcel->setWidth($widths);
        $head = [
            '内容id',
            '内容链接',
            '内容标题',
            '内容正文',
            '发布时间',
            'uid',
            '用户昵称',
            '点赞数',
            '评论数',
            '收藏数',
            'wiki链接'
        ];
        $data = [];
        $wikiLink = [];
        foreach ($photos as $photoId => $row) {
            $photo = $row['photo_info'];
            $userInfo = $row['user_info'];
            $counter = $row['counter'];
            $wikiInfo = $row['wiki_info']['list'];
            if ($wikiInfo) {
                foreach ($wikiInfo as $wiki) {
                    $link = Hhzurl::H5WikiDetails($wiki['id']);
                    $wikiLink[] = $link;
                }
            }

            $data[] = [
                $photoId,
                Hhzurl::h5PhotoShow($photoId),
                $photo['title']?self::filterEmoji($photo['title']):'',
                $photo['remark']?self::filterEmoji($photo['remark']):'',
                date('Y-m-d H:i:s', $photo['addtime']),
                $userInfo['uid'],
                $userInfo['nick']?:'',
                $counter['like'],
                $counter['comments'],
                $counter['favorite'],
                implode(',', $wikiLink),
            ];
        }

        $downExcel->create($data, $head);
        return back();
    }

    private static function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }

    // 正文中轻话题高亮
    private function highLight($remark)
    {
        preg_match_all('/#([\w\-]{1,15}+)/u', $remark . ' ', $userTags);

        if (isset($userTags[0]) && !empty($userTags[0])) {
            $replaceRemarkArr = [];
            foreach ($userTags[0] as $userTag) {
                $replaceRemarkArr[] = '<b style="color:deepskyblue;">' . $userTag . '</b>';
            }
            return str_replace($userTags[0], $replaceRemarkArr, $remark);
        }

        return $remark;
    }
}
